﻿//This C# code file was released under the Ms-PL license
//http://www.opensource.org/licenses/ms-pl.html
//This script was originally intended for use with Microsoft Dynamics AX
//and maintained and distributed as a project on CodePlex
//http://dynamicsaxadmin.codeplex.com

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Activities;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Build.Workflow.Activities;
using System.IO;

namespace CodeCrib.AX2009.TFS
{
    [BuildActivity(HostEnvironmentOption.Agent)]
    public class ExportLabels : CodeActivity
    {
        public InArgument<string> ConfigurationFile { get; set; }

        [RequiredArgument]
        public InArgument<string> LabelFilesFolder { get; set; }
        [RequiredArgument]
        public InArgument<string> ExportFilesFolder { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            string configurationFile = ConfigurationFile.Get(context);
            string labelFilesFolder = LabelFilesFolder.Get(context);
            string exportFilesFolder = ExportFilesFolder.Get(context);

            if (Directory.Exists(labelFilesFolder))
            {
                var serverConfig = Helper.GetServerConfig(configurationFile);

                foreach (string filename in Directory.GetFiles(labelFilesFolder, "*.ald"))
                {
                    if (!ImportLabels.IsEmptyLabelFile(filename))
                    {
                        context.TrackBuildMessage(string.Format("Exporting label file {0}", filename));

                        string labelFile = Path.GetFileNameWithoutExtension(filename).Substring(2, 3);
                        string labelLanguage = Path.GetFileNameWithoutExtension(filename).Substring(5);

                        CodeCrib.AX2009.Manage.AppFiles appFiles = new Manage.AppFiles(System.IO.Path.Combine(serverConfig.ApplicationFileLocation, "Appl", serverConfig.Application));
                        appFiles.ExportLabels(labelFile, labelLanguage, exportFilesFolder);
                    }
                }
            }
            else
            {
                context.TrackBuildWarning(string.Format("Label file folder {0} not found.", labelFilesFolder));
            }
        }
    }

    [BuildActivity(HostEnvironmentOption.Agent)]
    public class ExportLayer : CodeActivity
    {
        public InArgument<string> ConfigurationFile { get; set; }

        [RequiredArgument]
        public InArgument<string> ExportFolder { get; set; }
        [RequiredArgument]
        public InArgument<string> Layer { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            string configurationFile = ConfigurationFile.Get(context);
            string exportFolder = ExportFolder.Get(context);
            string layer = Layer.Get(context);

            var serverConfig = Helper.GetServerConfig(configurationFile);

            CodeCrib.AX2009.Manage.AppFiles appFiles = new Manage.AppFiles(System.IO.Path.Combine(serverConfig.ApplicationFileLocation, "Appl", serverConfig.Application));

            context.TrackBuildMessage(string.Format("Exporting layer {0}", layer));
            appFiles.ExportLayer(layer, exportFolder);
        }
    }

    [BuildActivity(HostEnvironmentOption.Agent)]
    public class InstallLayer : CodeActivity
    {
        public InArgument<string> ConfigurationFile { get; set; }

        [RequiredArgument]
        public InArgument<string> LayerFile { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            string configurationFile = ConfigurationFile.Get(context);
            string layerFile = LayerFile.Get(context);
            var serverConfig = Helper.GetServerConfig(configurationFile);

            var appFolder = System.IO.Path.Combine(serverConfig.ApplicationFileLocation, "Appl", serverConfig.Application);
            CodeCrib.AX2009.Manage.AppFiles appFiles = new Manage.AppFiles(appFolder);

            context.TrackBuildMessage(string.Format("Installing layer file {0}", layerFile));
            appFiles.InstallLayer(layerFile);

            var index = System.IO.Path.Combine(appFolder, "axapd.aoi");
            if (System.IO.File.Exists(index))
            {
                System.IO.File.Delete(index);
            }
        }
    }

    //[BuildActivity(HostEnvironmentOption.Agent)]
    //public class ExportModelStore : CodeActivity

    [BuildActivity(HostEnvironmentOption.Agent)]
    public class UninstallLayer : CodeActivity
    {
        public InArgument<string> ConfigurationFile { get; set; }

        [RequiredArgument]
        public InArgument<string> Layer { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            string configurationFile = ConfigurationFile.Get(context);
            string layer = Layer.Get(context);
            var serverConfig = Helper.GetServerConfig(configurationFile);

            var appFolder = System.IO.Path.Combine(serverConfig.ApplicationFileLocation, "Appl", serverConfig.Application);
            CodeCrib.AX2009.Manage.AppFiles appFiles = new Manage.AppFiles(appFolder);

            context.TrackBuildMessage(string.Format("Uninstalling layer {0}", layer));
            appFiles.UninstallLayer(layer);

            var index = System.IO.Path.Combine(appFolder, "axapd.aoi");
            if (System.IO.File.Exists(index))
            {
                System.IO.File.Delete(index);
            }
        }
    }

    //[BuildActivity(HostEnvironmentOption.Agent)]
    //public class ExportModelStore : CodeActivity

    [BuildActivity(HostEnvironmentOption.Agent)]
    public class RestoreAppFiles : CodeActivity
    {
        public InArgument<string> ConfigurationFile { get; set; }

        [RequiredArgument]
        public InArgument<string> Folder { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            string configurationFile = ConfigurationFile.Get(context);
            string sourceFolder = Folder.Get(context);
            var serverConfig = Helper.GetServerConfig(configurationFile);

            var appFolder = System.IO.Path.Combine(serverConfig.ApplicationFileLocation, "Appl", serverConfig.Application);

            context.TrackBuildMessage("Restoring application files");

            if (System.IO.Directory.Exists(appFolder))
            {
                System.IO.Directory.Delete(appFolder, true);
            }
            System.IO.Directory.CreateDirectory(appFolder);
            System.IO.Directory.CreateDirectory(System.IO.Path.Combine(appFolder, "Db"));
            System.IO.Directory.CreateDirectory(System.IO.Path.Combine(appFolder, "Old"));
            System.IO.Directory.CreateDirectory(System.IO.Path.Combine(appFolder, "Tmp"));

            var sourceAttributes = System.IO.File.GetAttributes(sourceFolder);
            if ((sourceAttributes & FileAttributes.Directory) == FileAttributes.Directory)
            {
                var files = System.IO.Directory.GetFiles(sourceFolder);
                foreach (var file in files)
                {
                    var filename = System.IO.Path.GetFileName(file);
                    if (!filename.Equals("axapd.aoi", StringComparison.InvariantCultureIgnoreCase))
                    {
                        System.IO.File.Copy(file, System.IO.Path.Combine(appFolder, filename));
                    }
                }
            }
            else if (Path.GetExtension(sourceFolder).Equals(".zip", StringComparison.InvariantCultureIgnoreCase))
            {
                System.IO.Compression.ZipFile.ExtractToDirectory(sourceFolder, appFolder);
            }
            Helper.RemoveReadOnlyFlags(appFolder, "*");
        }
    }
}
